<?php
namespace app\common\controller;

use think\Db;
use think\Controller;

class ApiCommon extends Controller
{


    /*
     * 积分处理方法
     * $user_id  用户id
     * $type     类型    : 1 新增 , 2 扣除
     * $int_type 积分类型 : 1 邀请新用户 ,
     * $integral 操作积分
     */
    public function integral($user_id,$type,$int_type,$integral)
    {

        // 获取当前积分
        $balance = $this->getIntegral($user_id);
        if($type == 2){
            if($balance<$integral){
                return ['code'=>'0','msg'=>'余额不足'];
            }
        }


        // 设置记录数据
        $data['user_id']     = $user_id;
        $data['type']        = $type;
        $data['int_type']    = $int_type;
        $data['integral']    = $integral;
        $data['balance']     = $type == 1 ? ($balance + $integral) : ($balance - $integral);
        $data['create_time'] = date('Y-m-d H:i:s');

        $res = Db::name('integral_record')->insert($data);

        if($res){
            return ['code'=>'1','msg'=>'操作成功'];
        }else{
            return ['code'=>'0','msg'=>'操作失败'];
        }


    }


    /*
     * 获取用户积分
     * $user_id 用户id
     */
    public function getIntegral($user_id)
    {

        $where[] = ['user_id','eq',$user_id];

        $res = Db::name('integral_record')->where($where)->order('id desc')->find();

        if($res){
            return $res['balance'];
        }else{
            return '0';
        }


    }


    /*
    *  JSAPI 支付
    * @string  openid    : 用户id
    * @string  order_num : 订单号
    * @string  price     : 支付金额
    */
    public function pay($openid,$order_num,$price)
    {
        require_once PAY_PATH."lib/WxPay.Api.php";
        require_once PAY_PATH."example/WxPay.JsApiPay.php";
        require_once PAY_PATH."example/WxPay.Config.php";
        require_once PAY_PATH.'example/log.php';

        try{
            $tools = new \JsApiPay();
            //②、统一下单
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("快蝌洗车");
            $input->SetAttach("快蝌洗车");
            $input->SetOut_trade_no($order_num);
            $input->SetTotal_fee($price*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetNotify_url("https://kkerp.youywt.com/api/notify/index.html");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openid);

            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            $jsApiParameters = $tools->GetJsApiParameters($order);
            return $jsApiParameters;

        } catch(\Exception $e) {
//            Log::ERROR(json_encode($e));
            return $e->getMessage();
        }
    }
}